package hn.cch.indicator;


import org.apache.commons.math3.stat.StatUtils;

import java.util.Collections;
import java.util.List;

/**
 * 条件风险价值：Conditional Value at Risk
 */
public class HistoricalCVaR {

    /**
     *
     * @param rateOfReturns 收益率Rate Of Return
     * @param confidenceInterval 1-置信区间Confidence Interval
     * @return
     */
    public Double calculate(List<Double> rateOfReturns, Double confidenceInterval){

        //1.收益率按从小到大排序
        Collections.sort(rateOfReturns);

        //
        int k = (int) Math.floor(rateOfReturns.size() * confidenceInterval);
        if (k == 0){
            return null;
        }
        // List<Double> 转 double[]
        double[] rors = new double[rateOfReturns.size()];
        for (int i = 0; i < rateOfReturns.size(); i++) {
            rors[i] = rateOfReturns.get(i);
        }
        double mean = StatUtils.mean(rors);
        return -mean;
    }
}
